package cn.xiehang.SoundSight;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ForgetPage extends AppCompatActivity {
    Button sendCode;
    Button resetPasswordButton;
    Button showOrHidPassword;
    Button showOrHidConfirmPassword;
    EditText email;
    EditText code;
    EditText password;
    EditText confirm_password;
    private ProgressDialog progressDialog;
    private String url = SeverURL.URL+"/send_reset_code";
    private String urlReset = SeverURL.URL+"/reset";
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.forgot_page);
        sendCode = findViewById(R.id.forgot_button);
        resetPasswordButton = findViewById(R.id.forgot_confirm_button);
        showOrHidPassword = findViewById(R.id.forget_password_show_or_hide);
        showOrHidConfirmPassword = findViewById(R.id.forget_password_confirm_show_or_hide);
        email = findViewById(R.id.forgot_email);
        code = findViewById(R.id.forgot_code);
        password = findViewById(R.id.forgot_password);
        confirm_password = findViewById(R.id.forgot_confirm_password);

        // 初始化 ProgressDialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("请稍等片刻...");
        progressDialog.setCancelable(false);

        showOrHidPassword.setOnClickListener(v -> {
            if (password.getInputType() == 129) {
                password.setInputType(128);
                showOrHidPassword.setBackground(getDrawable(R.drawable.show_password));
            } else {
                password.setInputType(129);
                showOrHidPassword.setBackground(getDrawable(R.drawable.hide_password));
            }
        });

        showOrHidConfirmPassword.setOnClickListener(v -> {
            if (confirm_password.getInputType() == 129) {
                confirm_password.setInputType(128);
                showOrHidConfirmPassword.setBackground(getDrawable(R.drawable.show_password));
            } else {
                confirm_password.setInputType(129);
                showOrHidConfirmPassword.setBackground(getDrawable(R.drawable.hide_password));
            }
        });
        sendCode.setOnClickListener(v -> {
            // 发送验证码
            String emailText = email.getText().toString();
            if (emailText.isEmpty()) {
                Toast.makeText(ForgetPage.this, "请输入邮箱/用户名", Toast.LENGTH_SHORT).show();
                return;
            }
            progressDialog.show();
            sendCode(emailText);
        });
        resetPasswordButton.setOnClickListener(v -> {
            // 重置密码
            String emailText = email.getText().toString();
            String codeText = code.getText().toString();
            String passwordText = password.getText().toString();
            String confirmPasswordText = confirm_password.getText().toString();
            if (emailText.isEmpty() || codeText.isEmpty() || passwordText.isEmpty() || confirmPasswordText.isEmpty()) {
                Toast.makeText(ForgetPage.this, "请填写完整信息", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!passwordText.equals(confirmPasswordText)) {
                Toast.makeText(ForgetPage.this, "两次密码不一致", Toast.LENGTH_SHORT).show();
                return;
            }
            progressDialog.show();
            resetPassword(emailText, codeText, passwordText);
        });
    }
    private void resetPassword(String email,String code,String password){
        // 发送验证码
        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient();

        // 创建 Gson 实例
        Gson gson = new Gson();

        // 创建一个 User 对象
        HashMap<String, String> postData = new HashMap<>();
        postData.put("username", email);
        postData.put("code", code);
        postData.put("password", password);

        // 将 User 对象转换为 JSON 字符串
        String json = gson.toJson(postData);

        // 创建一个 Request 对象
        Request request = new Request.Builder()
                .url(urlReset)
                .post(RequestBody.create(json, MediaType.parse("application/json")))
                .build();

        // 异步执行请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 请求失败时，关闭弹窗
                runOnUiThread(() -> {
                    progressDialog.dismiss();
                    // 显示错误信息或其他操作
                    Toast.makeText(ForgetPage.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                });
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                //如果状态码是400，表示登录失败，将返回信息转化为json格式，并打印message
                if (response.code() == 400) {
                    runOnUiThread(() -> {
                        progressDialog.dismiss();
                        // 显示错误信息或其他操作
                        String json = null;
                        try {
                            json = response.body().string();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Gson gson = new Gson();
                        HashMap<String, String> map = gson.fromJson(json, HashMap.class);
                        String message = map.get("message");
                        Toast.makeText(ForgetPage.this, message, Toast.LENGTH_SHORT).show();
                    });
                }

                runOnUiThread(() -> {
                    progressDialog.dismiss();
                    // 处理响应数据
                    if (response.isSuccessful()) {
                        Toast.makeText(ForgetPage.this, "重置成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                });
            }
        });

    }
    private void sendCode(String email) {
        // 发送验证码
        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient();

        // 创建 Gson 实例
        Gson gson = new Gson();

        // 创建一个 User 对象
        HashMap<String, String> postData = new HashMap<>();
        postData.put("username", email);

        // 将 User 对象转换为 JSON 字符串
        String json = gson.toJson(postData);

        // 创建一个 Request 对象
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(json, MediaType.parse("application/json")))
                .build();
        client = new OkHttpClient();
        // 异步执行请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 请求失败时，关闭弹窗
                runOnUiThread(() -> {
                    progressDialog.dismiss();
                    // 显示错误信息或其他操作
                    Toast.makeText(ForgetPage.this, e.toString(), Toast.LENGTH_SHORT).show();
                });
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                //如果状态码是400，表示登录失败，将返回信息转化为json格式，并打印message
                if (response.code() == 400) {
                    runOnUiThread(() -> {
                        progressDialog.dismiss();
                        // 显示错误信息或其他操作
                        String json = null;
                        try {
                            json = response.body().string();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Gson gson = new Gson();
                        HashMap<String, String> map = gson.fromJson(json, HashMap.class);
                        String message = map.get("message");
                        if (message.contains("已发送")) {
                            password.setVisibility(View.VISIBLE);
                            confirm_password.setVisibility(View.VISIBLE);
                            code.setVisibility(View.VISIBLE);
                            resetPasswordButton.setVisibility(View.VISIBLE);
                            showOrHidPassword.setVisibility(View.VISIBLE);
                            showOrHidConfirmPassword.setVisibility(View.VISIBLE);
                        }
                        Toast.makeText(ForgetPage.this, message, Toast.LENGTH_SHORT).show();
                    });
                }

                runOnUiThread(() -> {
                    progressDialog.dismiss();
                    // 处理响应数据
                    if (response.isSuccessful()) {
                        password.setVisibility(View.VISIBLE);
                        confirm_password.setVisibility(View.VISIBLE);
                        code.setVisibility(View.VISIBLE);
                        showOrHidPassword.setVisibility(View.VISIBLE);
                        showOrHidConfirmPassword.setVisibility(View.VISIBLE);
                        resetPasswordButton.setVisibility(View.VISIBLE);
                        Toast.makeText(ForgetPage.this, "发送成功，请在邮箱中查看相关信息", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

    }
}
